package hk.com.carfield.action.process;

import hk.com.carfield.core.Config;
import hk.com.carfield.core.Context;
import hk.com.carfield.util.LangUtil;
import hk.com.carfield.util.LogUtil;
import hk.com.carfield.web.Request;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author carfield
 */
public final class Session implements Process {
	public static final Map<String, AtomicInteger> triedMap = new ConcurrentHashMap<String, AtomicInteger>();

	public String actionCode() {
		return "session";
	}

	public boolean adminOnly() {
		return false;
	}

	public File process(final Context c, final Request req, final File l) {
		final String email = c.config.getAdminEmail();
		if (email != null && email.equals(req.getParameter("email"))) {
			// TODO log the remote IP if needed
			final String pwd = req.getParameter("password");
			LangUtil.incrementMap(Session.triedMap, pwd);
			req.setPassword(pwd);

			// TODO create another process for it??
			try {
				c.config = Config
						.getConfig(new File(c.config.dataRoot, "conf"));
			} catch (final IOException e) {
				LogUtil.error("cannot reload config", c.mailMan);
			}
		}
		return l;
	}
}